<template>
  <div class="mentor-apply-container">
    <div v-loading="dataLoading" class="mentor-apply-wrapper">
      <template v-if="!dataLoading && batchInfo">
        <!-- 头部 -->
        <div class="mentor-apply-header">
          <div class="title">《{{ batchInfo.batchName }}》{{ t('mentorApply.firstTitle') }}</div>
          <div class="tips">
            <span>{{ t('mentorApply.welcome') }}</span>
            <el-button
              v-if="batchInfo.applyTemplateUrl"
              link
              type="primary"
              @click="downloadTemplate"
            >
              《{{ t('mentorApply.downloadTemplate') }}》
            </el-button>
          </div>
        </div>
        <!-- 表单 -->
        <div class="bg-wrapper">
          <el-scrollbar class="mentor-apply-scroll">
            <el-form
              ref="formRef"
              :disabled="submitLoading"
              :model="formData"
              :rules="formRules"
              label-width="120px"
              label-position="top"
              class="form-section"
            >
              <!-- 批次信息 -->
              <div class="mb-30px">
                <div class="flex items-center gap-8px mb-4">
                  <el-icon size="18px" color="#8E1B11"><Document /></el-icon>
                  <div class="text-18px line-height-none text-[#8E1B11]">{{
                    t('mentorApply.batchInfoTitle')
                  }}</div>
                </div>
                <el-form-item :label="t('mentorApply.batchInfo.applyStartTime')">
                  <el-input
                    :value="formatDate(batchInfo.applyStartTime)"
                    :placeholder="t('mentorApply.batchInfo.applyStartTime')"
                    disabled
                  />
                </el-form-item>
                <el-form-item :label="t('mentorApply.batchInfo.applyEndTime')">
                  <el-input
                    :value="formatDate(batchInfo.applyEndTime)"
                    :placeholder="t('mentorApply.batchInfo.applyEndTime')"
                    disabled
                  />
                </el-form-item>
                <el-form-item :label="t('mentorApply.batchInfo.reviewStartTime')">
                  <el-input
                    :value="formatDate(batchInfo.reviewStartTime)"
                    :placeholder="t('mentorApply.batchInfo.reviewStartTime')"
                    disabled
                  />
                </el-form-item>
                <el-form-item :label="t('mentorApply.batchInfo.reviewEndTime')">
                  <el-input
                    :value="formatDate(batchInfo.reviewEndTime)"
                    :placeholder="t('mentorApply.batchInfo.reviewEndTime')"
                    disabled
                  />
                </el-form-item>
              </div>
              <!-- 账号信息 -->
              <div class="mb-30px">
                <div class="flex items-center gap-8px mb-4">
                  <el-icon size="18px" color="#8E1B11"><Document /></el-icon>
                  <div class="text-18px line-height-none text-[#8E1B11]">{{
                    t('mentorApply.accountTitle')
                  }}</div>
                </div>
                <el-form-item :label="t('mentorApply.fields.username')" prop="username">
                  <el-input
                    v-model="formData.username"
                    :placeholder="
                      t('common.inputTextPlaceholder') + t('mentorApply.fields.username')
                    "
                  />
                </el-form-item>
                <el-form-item :label="t('mentorApply.fields.password')" prop="password">
                  <el-input
                    v-model="formData.password"
                    :placeholder="
                      t('common.inputTextPlaceholder') + t('mentorApply.fields.password')
                    "
                  />
                </el-form-item>
                <el-form-item
                  :label="t('mentorApply.fields.confirmPassword')"
                  prop="confirmPassword"
                >
                  <el-input
                    v-model="formData.confirmPassword"
                    :placeholder="
                      t('common.inputTextPlaceholder') + t('mentorApply.fields.confirmPassword')
                    "
                  />
                </el-form-item>
              </div>
              <!-- 个人信息 -->
              <div class="mb-30px">
                <div class="flex items-center gap-8px mb-4">
                  <el-icon size="18px" color="#8E1B11"><Document /></el-icon>
                  <div class="text-18px line-height-none text-[#8E1B11]">{{
                    t('mentorApply.personalTitle')
                  }}</div>
                </div>
                <el-form-item :label="t('mentorApply.fields.nickName')" prop="nickName">
                  <el-input
                    v-model="formData.nickName"
                    :placeholder="
                      t('common.inputTextPlaceholder') + t('mentorApply.fields.nickName')
                    "
                  />
                </el-form-item>
                <el-form-item :label="t('mentorApply.fields.email')" prop="email">
                  <el-input
                    v-model="formData.email"
                    :placeholder="t('common.inputTextPlaceholder') + t('mentorApply.fields.email')"
                  />
                </el-form-item>
                <el-form-item :label="t('mentorApply.fields.mobile')" prop="mobile">
                  <el-input
                    v-model="formData.mobile"
                    :placeholder="t('common.inputTextPlaceholder') + t('mentorApply.fields.mobile')"
                  />
                </el-form-item>
                <el-form-item :label="t('mentorApply.fields.identity')" prop="identity">
                  <el-input
                    v-model="formData.identity"
                    :placeholder="
                      t('common.inputTextPlaceholder') + t('mentorApply.fields.identity')
                    "
                  />
                </el-form-item>
                <el-form-item :label="t('mentorApply.fields.title')" prop="title">
                  <el-input
                    v-model="formData.title"
                    :placeholder="t('common.inputTextPlaceholder') + t('mentorApply.fields.title')"
                  />
                </el-form-item>
              </div>
              <!-- 申请信息 -->
              <div class="mb-30px">
                <div class="flex items-center gap-8px mb-4">
                  <el-icon size="18px" color="#8E1B11"><Document /></el-icon>
                  <div class="text-18px line-height-none text-[#8E1B11]">{{
                    t('mentorApply.applyTitle')
                  }}</div>
                </div>
                <el-form-item :label="t('mentorApply.fields.applyMajor')" prop="applyMajor">
                  <el-input
                    v-model="formData.applyMajor"
                    :placeholder="
                      t('common.inputTextPlaceholder') + t('mentorApply.fields.applyMajor')
                    "
                  />
                </el-form-item>
                <el-form-item :label="t('mentorApply.fields.deptId')" prop="deptId">
                  <el-tree-select
                    v-model="formData.deptId"
                    :data="deptTree"
                    :props="defaultProps"
                    check-strictly
                    default-expand-all
                    :placeholder="
                      t('common.selectTextPlaceholder') + t('mentorApply.fields.deptId')
                    "
                    value-key="id"
                  />
                </el-form-item>
                <el-form-item :label="t('mentorApply.fields.highestDegree')" prop="highestDegree">
                  <el-input
                    v-model="formData.highestDegree"
                    :placeholder="
                      t('common.inputTextPlaceholder') + t('mentorApply.fields.highestDegree')
                    "
                  />
                </el-form-item>
                <el-form-item
                  :label="t('mentorApply.fields.applicationFormUrl')"
                  prop="applicationFormUrl"
                >
                  <MentorApplyUpload
                    v-model="formData.applicationFormUrl"
                    :limit="1"
                    :fileType="['pdf']"
                  />
                </el-form-item>
                <el-form-item :label="t('mentorApply.fields.appendixUrl')" prop="appendixUrl">
                  <MentorApplyUpload
                    v-model="formData.appendixUrl"
                    :limit="1"
                    :fileType="['pdf']"
                  />
                </el-form-item>
              </div>
            </el-form>
          </el-scrollbar>
        </div>
        <!-- 底部 -->
        <div class="footer">
          <el-button
            type="primary"
            :disabled="!batchInfo"
            :loading="submitLoading"
            @click="handleSubmit"
          >
            {{ t('mentorApply.submitBtn') }}
          </el-button>
        </div>
      </template>

      <!-- 没查到batchInfo -->
      <div v-else class="mentor-apply-scroll flex items-center justify-center">
        <el-empty :image-size="200" :description="t('mentorApply.message.noBatchInfo')" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { MentorApplyDTO, PickBatchDetailVO, MentorApplyApi } from '@/api/mentorApply'
import { defaultProps, handleTree } from '@/utils/tree'
import { formatDate } from '@/utils/formatTime'
import { FormRules } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import MentorApplyUpload from '@/components/IMRUpload/MentorApplyUpload.vue'
import { useUserStore } from '@/store/modules/user'

defineOptions({ name: 'MentorPickApply' })

const route = useRoute() // 路由
const router = useRouter() // 路由
const { t } = useI18n() // 国际化

const userStore = useUserStore()

const batchId = ref('') // 批次ID
const batchInfo = ref<PickBatchDetailVO>() // 批次详情
const deptTree = ref<any[]>([]) // 部门列表
const dataLoading = ref(false) // 数据加载中
const submitLoading = ref(false) // 提交中
const formRef = ref()
const formData = ref({
  username: undefined,
  password: undefined,
  confirmPassword: undefined,
  nickName: undefined,
  email: undefined,
  mobile: undefined,
  identity: undefined,
  title: undefined,
  applyMajor: undefined,
  deptId: undefined,
  highestDegree: undefined,
  applicationFormUrl: undefined,
  appendixUrl: undefined
})

// 表单校验
const equalToPassword = (_rule, value, callback) => {
  if (formData.value.confirmPassword !== value) {
    callback(new Error(t('profile.password.diffPwd')))
  } else {
    callback()
  }
}

const formRules = reactive<FormRules>({
  username: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('mentorApply.fields.username'),
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('mentorApply.fields.password'),
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('mentorApply.fields.confirmPassword'),
      trigger: 'blur'
    },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ],
  nickName: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('mentorApply.fields.nickName'),
      trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('mentorApply.fields.email'),
      trigger: 'blur'
    }
  ],
  mobile: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('mentorApply.fields.mobile'),
      trigger: 'blur'
    }
  ],
  identity: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('mentorApply.fields.identity'),
      trigger: 'blur'
    }
  ],
  title: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('mentorApply.fields.title'),
      trigger: 'blur'
    }
  ],
  applyMajor: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('mentorApply.fields.applyMajor'),
      trigger: 'blur'
    }
  ],
  deptId: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('mentorApply.fields.deptId'),
      trigger: 'change'
    }
  ],
  highestDegree: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('mentorApply.fields.highestDegree'),
      trigger: 'blur'
    }
  ],
  applicationFormUrl: [
    {
      required: true,
      message: t('common.uploadFile') + t('mentorApply.fields.applicationFormUrl'),
      trigger: 'change'
    }
  ],
  appendixUrl: [
    {
      required: true,
      message: t('common.uploadFile') + t('mentorApply.fields.appendixUrl'),
      trigger: 'change'
    }
  ]
})

// 获取批次详情
const getDetail = async () => {
  dataLoading.value = true
  try {
    batchInfo.value = await MentorApplyApi.getPickBatch(batchId.value)
    const data = await MentorApplyApi.getDepartment()
    deptTree.value = handleTree(data)
  } catch (e) {}
  dataLoading.value = false
}

// 下载申请表模板
const downloadTemplate = () => {
  if (!batchInfo.value?.applyTemplateUrl) return
  const attachment = JSON.parse(batchInfo.value.applyTemplateUrl)
  if (attachment.length) {
    const file = attachment[0]
    let a = document.createElement('a');
    a.setAttribute('href', file.url);//文件下载地址
    a.setAttribute('target', '_blank');
    a.setAttribute('download', file.name);//修改文件名
    document.body.appendChild(a);
    a.click();
    a.remove();
  }
}

// 提交申请
const handleSubmit = async () => {
  // 提交申请
  const validate = await formRef.value?.validate()
  if (!validate) return
  // 校验
  submitLoading.value = true
  try {
    const data = { batchId: batchId.value, ...formData.value } as unknown as MentorApplyDTO
    await MentorApplyApi.createApply(data)
    ElMessageBox.alert(
      `<div>${t('mentorApply.fields.username')}: ${data.username}</div><div>${t('mentorApply.fields.password')}: ${data.password}</div><div><strong style="color: #8E1B11">${t('mentorApply.message.tips')}</strong></div>`,
      t('mentorApply.message.submitSuccess'),
      {
        dangerouslyUseHTMLString: true,
        showClose: false,
        center: true,
        confirmButtonText: t('mentorApply.message.toLogin'),
        customStyle: { width: '350px' }
      }
    ).then(() => {
      router.replace('/login')
    })
  } catch (e) {}
  submitLoading.value = false
}

onMounted(() => {
  userStore.cacheAndStateClear()
  const id = route.params.batchId as string
  if (id) {
    batchId.value = id
    getDetail()
  }
})
</script>

<style scoped lang="scss">
.mentor-apply-container {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 100vh;
  background-color: var(--el-bg-color-page);
}

.mentor-apply-wrapper {
  max-width: 800px;
  width: 100%;
  background-color: #ffffff;

  .mentor-apply-header {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 80px;
    padding-top: 20px;

    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 1px;
      background-color: #ebeef5;
    }

    .title {
      font-size: 20px;
      line-height: 24px;
      font-weight: bold;
      text-align: center;
      color: var(--el-color-primary);
    }

    .tips {
      margin-top: 8px;
      display: flex;
      align-items: center;
      font-size: 14px;
      line-height: 14px;
      color: #666666;
    }
  }
}

.bg-wrapper {
  padding: 10px 10px 0;
}

.mentor-apply-scroll {
  box-sizing: border-box;
  padding: 10px 20px 0 10px;
  height: calc(100vh - 150px);
}

.footer {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
  box-shadow: 0px -1px 0px #ebeef5;
}
</style>
